<template>
    <div>
      <el-form>
        <el-row :gutter="20">
            <el-col :xs="12" :sm="12" :lg="12" class="col-box">
                <span class="col-span">项目需求：</span>
                <el-select v-model="addProject" style="width:80%" placeholder="请选择" @change="changeProjectFilter">
                    <el-option
                    v-for="(v,i) in project_list"
                    :key="i"
                    :label="v.project_workflow.project_name + '（' + (v.technical_field ? v.technical_field.name : '') + '）'"
                    :value="v.id">
                    </el-option>
                </el-select>
            </el-col>
            <!-- <el-col :xs="12" :sm="10" :lg="10" class="col-box">
                <span class="col-span">时间段：</span>
                <el-date-picker
                    v-model="date_range"
                    @change="changeDateRange"
                    type="daterange"
                    range-separator="至"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期">
                </el-date-picker>
            </el-col> -->
            <el-col :xs="12" :sm="12" :lg="12" style="text-align: right;margin-bottom: 20px">
                <span v-if="isOprate">
                    <el-popconfirm v-if="isChildCheck" style="margin-left: 10px;" title="确定删除吗？" @onConfirm="delSubmit()">
                        <el-button slot="reference" :disabled="selectIds.length == 0" type="danger">
                            批量删除
                        </el-button>
                    </el-popconfirm>
                    <el-button v-if="isChildCheck" @click="chooseCancel()" type="warning">取消</el-button>
                    <span v-if="isModCheck">
                        <!-- <el-button v-if="!isCheck" @click="modAll()" type="primary" :disabled="selectIds.length == 0">批量修改</el-button>
                        <el-button v-if="!isCheck" @click="chooseCancel()" type="warning">取消</el-button> -->
                        <el-button @click="modSubmit()" type="primary" :disabled="selectIds.length == 0">确定修改</el-button>
                        <el-button @click="chooseCancel()" type="warning">取消</el-button>
                    </span>
                    <span v-if="isParentCheck">
                        <!-- <el-button v-if="!isCheck" @click="addAll()" type="success" :disabled="selectWeeks.length == 0">批量新增</el-button> -->
                        <!-- <el-button v-if="!isCheck" @click="chooseCancel()" type="warning">取消</el-button> -->
                        <el-button @click="addSubmit()" type="success" :disabled="selectWeeks.length == 0">确定新增</el-button>
                        <el-button @click="chooseCancel()" type="warning">取消</el-button>
                    </span>
                </span>
                <span v-else>
                    <el-button @click="addChoose()" type="success">新增</el-button>
                    <el-button @click="modChoose()" type="primary">修改</el-button>
                    <el-button @click="delChoose()" type="danger">删除</el-button>
                </span>   
            </el-col>
        </el-row>
        <el-table
        ref="multipleTable"
        max-height="500"
        v-loading="loading"
        :data="tableData"
        :header-cell-style="{background:'#eef1f6'}"
        border        
        default-expand-all
        lazy
        row-key="id"  
        :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
        @select-all="handleSelectionAll"
        @select="handleSelectionChange">
        <el-table-column
            v-if="isChildCheck || isParentCheck || isModCheck"
            type="selection"
            align="center"
            :selectable="checkFun"
            width="55">
        </el-table-column>
        <el-table-column label="周" align="center" width="250">
            <template slot-scope="scope">
                <span v-if="scope.row.type == 'parent'">{{ week2date(scope.row.week_display) }}</span> 
            </template> 
        </el-table-column>
        <el-table-column align="center" label="项目">
            <template slot-scope="scope">
                <el-form-item 
                    v-if="scope.row.type =='children' && scope.row.isAdd"
                    :style="error ? 'marginBottom: 30px' : 'marginBottom: 0'" 
                    prop="project_name">
                    <el-select v-model="addProject" style="width:80%" disabled placeholder="请选择" @change="changeProjectFilter">
                        <el-option
                        v-for="(v,i) in project_list"
                        :key="i"
                        :label="v.project_workflow.project_name + '（' + (v.technical_field ? v.technical_field.name : '') + '）'"
                        :value="v.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <template v-if="scope.row.type =='children' && !scope.row.isAdd">
                    <span>{{ scope.row.project_name + '——【' + scope.row.technical_field.name + '】' }}</span>
                    
                </template>
            </template>
        </el-table-column>
        <el-table-column align="center" label="分配人周">
            <template slot-scope="scope">
                <el-form-item 
                v-if="scope.row.type =='children' && scope.row.isSelect"
                    :style="error ? 'marginBottom: 30px' : 'marginBottom: 0'" 
                    prop="spend">
                    <el-input v-model="addSpend" autocomplete="off" 
                    oninput="value=value.replace(/^0[0-9]|^[2-9]|^1[0-9]|^1\.|[^\d.]/g,'')"
                    placeholder="输入小于等于1的正数"></el-input>
                </el-form-item>
                <span v-else>{{ scope.row.spend }}</span>
            </template>
        </el-table-column>
        <!-- <el-table-column width="200" align="center" label="操作">
            <template slot-scope="scope">
                <div class="action-btn" v-if="scope.row.type == 'children' && !scope.row.isAdd">
                    <el-popconfirm style="margin-left: 10px;" title="确定删除吗？" @onConfirm="delConfirm(scope.row.id)">
                        <el-button slot="reference" @click="delChange(scope.row, scope.$index, true)" size="mini" round type="danger">
                            删除
                        </el-button>
                    </el-popconfirm>
                </div>
            </template> 
        </el-table-column> -->
        </el-table>
        <el-pagination class="marT"
        v-show="dialogTotal > 10"
        :page-size="dialogSize"
        background                              
        @size-change="dialogSizeChange"
        @current-change="dialogCurrentChange"
        :current-page="dialogCurrent"                               
        layout="prev, pager, next"
        style="text-align: center"
        :total="dialogTotal">
        </el-pagination>
        
      </el-form>
    </div>
    
</template>

<script>
import { getHeaderName } from '@/app.config'
import { DateUtil } from '../utils.js'
export default {
    name: 'Talent',
    props: {
        projectList: Array,
        dateRange: Array,
        employee_id: '',
        project_id: ''
    },
    data() {
        return {
            loading: false,
            project_list: [],
            error: false,
            date_range: [],
            tableData: [],
            dialogCurrent: 1,
            dialogSize: 10,
            dialogTotal: 0,
            weekList: [],
            addSpend: '1',
            addProject: '',
            selectWeeks: [],
            selectIds: [],
            isOprate: false,
            isCheck: false,
            isParentCheck: false,
            isChildCheck: false,
            isModCheck: false,
            checkedKeys: false
        }
    },
    mounted() {
        this.initPro()
         
    },
    methods: {
        week2date(val) {
              let arr = val.split("-")
              let year = arr[0]
              let week = arr[1]

            let betDay = new Date(year+1+'-01-01 00:00:00').getTime() - new Date(year+'-01-01 00:00:00').getTime()
            let newD1 = new Date(year,0,1)
            let newD2 = new Date(year,11,31)
            
              let dayMS=24*60*60*1000
              let firstDay=firstDay=(7-newD1.getDay())*dayMS
            let weekMS=0
            if(newD1.getDay() < 4) {
                weekMS=(week-2)*7*dayMS
            } else {
                weekMS=(week-1)*7*dayMS
            }
              let result=newD1.getTime()+firstDay+weekMS+5*dayMS
            newD1.setTime(result)
            return val + '周\n(' + newD1.getFullYear() + "/" + (newD1.getMonth()+1) + "/" +newD1.getDate() + ')'
        },
        initPro() {
            this.loading = true
            this.$axios({
                url: `${process.env.VUE_APP_SOURSE_MANAGE_HOST}/api/v1/employee/${this.employee_id}/project/demand`,
                method: "get",
                headers: getHeaderName()
            }).then(res => {
                this.project_list = res.data.data
                if(this.project_id) {
                    this.addProject = this.project_id
                    this.date_range = this.dateRange
                    this.initWeek()
                } else {
                    this.weekList = DateUtil.estLabourWeek(this.dateRange[0],this.dateRange[1])
                    this.initTable()
                }
            })
        },
        initWeek(){
            this.loading = true
            this.$axios({
                url: `${process.env.VUE_APP_SOURSE_MANAGE_HOST}/api/v1/project/demand/${this.addProject}/needweek`,
                method: "get",
                headers: getHeaderName()
            }).then(res => {
                this.weekList = res.data.data
                this.initTable()
            })
        },
        initTable(){
            this.loading = true
            this.$axios({
                url: process.env.VUE_APP_SOURSE_MANAGE_HOST + '/api/v1/employee/assign',
                method: "get",
                headers: getHeaderName(),
                params: {
                    week_range: this.weekList.join() || '',
                    employee_id: this.employee_id
                }
            }).then(res => {
                this.loading = false
                this.tableData = res.data.data
                if(this.tableData) {
                    this.tableData.forEach(val => {
                        if(val.children) {
                            val.children.map((v) => {
                                v.isDel = false
                            })
                            
                        }
                        
                    })
                }
                
            })
        },
        checkFun(row,index) {
            if(this.isChildCheck) {
                if(row.type == 'parent') {
                    return false
                } else {
                    return true
                }
            }
            if(this.isModCheck) {
                if(row.type == 'parent' || (row.project_id != this.addProject)) {
                    return false
                } else {
                    return true
                }
            }
            if(this.isParentCheck) {
                if(row.type == 'children') {
                    return false
                } else {
                    if(row.type == 'parent') {
                        let flag = true
                        if(row.children && row.children.length > 0) {
                            row.children.map((v,i) => {
                                flag = flag && (v.project_id != this.addProject)
                            })
                        }
                        
                        return flag
                    } else {
                        return true
                    }
                    
                }
            } 
        },
        handleSelectionChange(val) {
            // if(this.isCheck) {
            //     return false
            // }
            if(this.isParentCheck) {
                let paids = []
                val.map((v) => {
                    if(v.type == 'parent' && !paids.includes(v.week_display)) {
                        let flag = true                 
                        if(v.children && v.children.length > 0) {
                            v.children.map((j) => {
                                flag = flag && (j.project_id != this.addProject)
                            })
                        }
                        if(flag) {
                            paids.push(v.week_display)
                        }
                    }
                    
                })
                this.selectWeeks = paids
                this.addAll()
            }
            
            if(this.isModCheck) {
                let ids = []
                val.map((v,i) => {
                    if(v.project_id == this.addProject && !ids.includes(v.id)) {
                        ids.push(v.id)
                    }
                })
                this.selectIds = ids
                this.modAll()
            } else {
                let ids = []
                val.map((v) => {
                    if(!ids.includes(v.id)) {
                        ids.push(v.id)
                    }
                })
                this.selectIds = ids
            }
        },
        handleSelectionAll() {
            this.checkedKeys = !this.checkedKeys;
            this.splite(this.tableData, this.checkedKeys);
            this.selectWeeks = []
            this.selectIds = []
            if(this.checkedKeys) {
                this.tableData.map((v) => {
                    let flag = true                 
                    if(v.children && v.children.length > 0) {
                        v.children.map((j) => {
                            flag = flag && (j.project_id != this.addProject)
                            if(this.isModCheck) {
                                if(j.project_id == this.addProject) {
                                    this.selectIds.push(j.id)
                                }
                            } else {
                                this.selectIds.push(j.id)
                            }
                            
                        })
                    }
                    if(flag) {
                        this.selectWeeks.push(v.week_display)
                    }
                })
                
            }
            if(this.isParentCheck) {
                this.addAll()
            }
            if(this.isModCheck) {
                this.modAll(true)
            }
            
        },
        splite(data, flag) {
            data.forEach((row) => {
                this.$refs.multipleTable.toggleRowSelection(row, flag);
                if (row.children && row.children.length > 0) {
                    this.splite(row.children,flag);
                }
            });
        },
        dialogCurrentChange(val) {
            this.dialogCurrent = val
            if(this.selectValue == 'technical_field') {
                this.initSingleTable()
            } else {
                this.initTable()
            }
        },
        dialogSizeChange(val) {
            this.dialogSize = val
            if(this.selectValue == 'technical_field') {
                this.initSingleTable()
            } else {
                this.initTable()
            }
        },
        delChoose() {
            if(!this.addProject) {
                this.$message.warning("请先选择项目需求")
                return false
            }
            this.isOprate = true
            this.isChildCheck = true
            this.isParentCheck = false
            this.isModCheck = false
            this.handleSelectionAll()
        },
        delSubmit() {
            this.loading = true
            this.$axios({
                url: `${process.env.VUE_APP_SOURSE_MANAGE_HOST}/api/v1/employee/assign/delete`,
                method: "post",
                headers: getHeaderName(),
                data: { 
                    'ped_ids': this.selectIds.join(), 
                }
            }).then(res => {
                if(res.data.code == 200) {
                    this.$message.success(res.data.message)
                    this.checkedKeys = false
                    this.isParentCheck = false
                    this.isModCheck = false
                    this.isChildCheck = false
                    this.isOprate = false
                    this.isCheck = false
                    this.selectWeeks = []
                    this.selectIds = []
                    this.initTable()
                } else {
                  this.$message.error(res.data.message)
                }
                this.loading = false
                
            })
        },
        delConfirm(id) {
            this.$axios({
                url: `${process.env.VUE_APP_SOURSE_MANAGE_HOST}/api/v1/employee/assign/${id}`,
                method: "delete",
                headers: getHeaderName()
            }).then(res => {
                if(res.data.code == 200) {
                  this.$message.success(res.data.message)
                  
                } else {
                 this.$message.error(res.data.message)
                }
                this.initTable()
            })
            
        },
        delChange(row, index, type) {
            let list,ind
            this.tableData.map((val,i) => {
                if(row.week_display == val.week_display && val.type == 'parent') {
                    list = val
                    ind = i
                }
            })
            list['children'].map((v) => {
                if(v.id == row.id) {
                    v.isDel = type
                }
            })
            this.$set(this.tableData, ind, list)
        },
        modChoose() {
            if(!this.addProject) {
                this.$message.warning("请先选择项目需求")
                return false
            }
            this.isOprate = true
            this.isModCheck = true
            this.isChildCheck = false
            this.isParentCheck = false
            // this.handleSelectionAll()
            this.modAll()
            
        },
        modAll(type) {
            this.tableData.map((v,i) => {
                if(v['children'] && v['children'].length > 0) {
                    v['children'].map((j,i2) => {
                        if(this.selectIds.includes(j.id)) {
                            this.$set(j, 'isSelect', true)
                        } else {
                            this.$set(j, 'isSelect', false)
                        }
                        if(type) {
                            this.$refs.multipleTable.toggleRowSelection(j, this.checkedKeys);
                        } else {
                            this.$refs.multipleTable.toggleRowSelection(j, j.isSelect);
                        }
                        
                    })
                }
            })
        },
        modSubmit() {
            if(!this.addSpend) {
                this.$message.error('请填写分配人周')
                return false
            }
            this.loading = true
            this.$axios({
                url: `${process.env.VUE_APP_SOURSE_MANAGE_HOST}/api/v1/employee/assign/update`,
                method: "post",
                headers: getHeaderName(),
                data: {
                    'ped_ids': this.selectIds.join(), 
                    'project_id': this.addProject, 
                    'spend': this.addSpend
                }
            }).then(res => {
                if(res.data.status == 'success') {
                    this.$message.success(res.data.message)
                    this.addSpend = '1'
                    this.checkedKeys = false
                    this.isParentCheck = false
                    this.isChildCheck = false
                    this.isModCheck = false
                    this.isOprate = false
                    this.isCheck = false
                    this.selectWeeks = []
                    this.selectIds = []
                    this.initTable()
                  
                } else {
                  this.$message({
                    showClose: true,
                    dangerouslyUseHTMLString: true,
                    message: res.data.message,
                    type: 'warning',
                    duration: 1000 * 10,
                  });
                }
                this.loading = false
                
            })
        },
        modCancel() {
            this.checkedKeys = false
            this.isCheck = false
            this.isChildCheck = false
            this.isModCheck = false
            this.isParentCheck = false
            this.isOprate = false
            this.selectWeeks = []
            this.selectIds = []
            this.initTable()
        },
        addChoose() {
            if(!this.addProject) {
                this.$message.warning("请先选择项目需求")
                return false
            }
            this.isChildCheck = false
            this.isModCheck = false
            this.isParentCheck = true
            this.isOprate = true
            this.handleSelectionAll()
            this.addAll()
        },
        addAll() {
            //this.isCheck = true
            this.tableData.map((v,i) => {
                if(this.selectWeeks.includes(v.week_display)) {
                    if(!v['children']) {
                        v['children'] = []
                    }
                    let flag = false
                    v['children'].map((v1,i1) => {
                        flag = flag || v1.isAdd
                        if(v1.isAdd) {
                            v1.isSelect = true
                        }
                    })
                    if(!flag) {
                        v['children'].push({
                            id: v.week_display+i,
                            project_name: "",
                            spend: '',
                            isAdd: true,
                            isSelect: true,
                            type: "children",
                            week_display: v.week_display,
                        })
                    }
                    
                } else {
                    if(v['children']) {
                        v['children'].map((j,k) => {
                            j.isSelect = false
                            
                        })
                    }
                }
                this.$set(this.tableData, i, v)
            })
        },
        addSubmit() {
            if(!this.addProject) {
                this.$message.error('请选择项目')
                return false
            }
            if(!this.addSpend) {
                this.$message.error('请填写分配人周')
                return false
            }
            this.loading = true
            this.$axios({
                url: `${process.env.VUE_APP_SOURSE_MANAGE_HOST}/api/v1/employee/assign`,
                method: "post",
                headers: getHeaderName(),
                data: {
                    'week_display': this.selectWeeks.join(), 
                    'employee_id': this.employee_id, 
                    'project_id': this.addProject, 
                    'spend': this.addSpend
                }
            }).then(res => {
                if(res.data.status == 'success') {
                    this.$message.success(res.data.message)
                    this.addSpend = '1'
                    this.checkedKeys = false
                    this.isParentCheck = false
                    this.isChildCheck = false
                    this.isModCheck = false
                    this.isOprate = false
                    this.isCheck = false
                    this.selectWeeks = []
                    this.selectIds = []
                    this.initTable()
                  
                } else {
                  this.$message({
                    showClose: true,
                    dangerouslyUseHTMLString: true,
                    message: res.data.message,
                    type: 'warning',
                    duration: 1000 * 10,

                  });
                }
                this.loading = false
                
            })
        },
        addCancel() {
            this.checkedKeys = false
            this.isCheck = false
            this.isParentCheck = false
            this.isChildCheck = false
            this.isModCheck = false
            this.isOprate = false
            this.selectWeeks = []
            this.selectIds = []
            this.initTable()
        },
        chooseCancel() {
            this.checkedKeys = false
            this.isParentCheck = false
            this.isChildCheck = false
            this.isModCheck = false
            this.isOprate = false
            this.isCheck = false
            this.selectWeeks = []
            this.selectIds = []
            this.initTable()
        },
        changeProjectFilter(value) {
            this.checkedKeys = false
            this.isParentCheck = false
            this.isChildCheck = false
            this.isModCheck = false
            this.isOprate = false
            this.isCheck = false
            this.selectWeeks = []
            this.selectIds = []
            if(value) {
                this.addProject = value
                this.initWeek()
            } else {
                this.params.pageNo = 1
                this.initWeek()
            }
        },
        changeDateRange(e) {
        
        },

    },
    watch: {

    }
}
</script>
<style lang="scss" scoped>
/deep/ .el-table .cell {
  white-space: pre-line;
}
.col-box {
  display: flex;
  margin-bottom: 10px;
  .col-span {
    min-width: 100px;
    line-height: 36px;
  }
}
.form-box {
    padding: 0 20px 20px 20px;
}
.form-title {
    font-size: 18px;
    margin: 10px 0 30px 0;
}
.form-item {
    display: flex;
    min-height: 50px;
}
.form-btn {
    text-align: right;
}
.el-tag + .el-tag {
    margin-left: 10px;
}
.button-new-tag {
    margin-left: 10px;
    height: 32px;
    line-height: 30px;
    padding-top: 0;
    padding-bottom: 0;
}
.input-new-tag {
    width: 90px;
    margin-left: 10px;
    vertical-align: bottom;
}
.action-btn {
    margin-right: 10px;
}
</style>


